package com.example.pad_sys;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.pad_sys.databinding.ActivityMainBinding;

import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {

    private static final String[] array = {
            "存货编码：",
            "存货名称：",
            "规格型号：",
            "计量单位：",
            "数量：",
            "批次号：",
            "生产日期：",
            "公司名称：",
    };

    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(LayoutInflater.from(this));
        setContentView(binding.getRoot());
        binding.btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initView(null);
            }
        });
        initView(null);
        initScanEditView();
    }

    private void initView(String[] values){
        binding.scrollLayout.removeAllViews();
        if (values == null) {
            for (int i = 0; i < array.length; i++) {
                binding.scrollLayout.addView(getItemInputLayout(i, array[i], "", null, ItemInputLayout.MODE_TEXT, false));
            }
        } else {
            for (int i = 0; i < array.length; i++) {
                binding.scrollLayout.addView(getItemInputLayout(i, array[i], values[i], null, ItemInputLayout.MODE_TEXT, false));
            }
        }
    }

    private void initScanEditView() {
        // 存货编码|存货名称|规格型号|计量单位|数量|批次号|生产日期|供应商名称
//        binding.etCode.setText("0307050521|制冷剂 CO2|R22|个|10ss|20220618|2022/07/02|徐州市新长晟化工有限公司");
//        binding.etCode.setText("0307050521|制冷剂CO2|制冷机RWFⅡ134E|个|4.5||2022/07/02|徐州市新长晟化工有限公司");
//        binding.etCode.setText("0403100126|方替代|制冷机RWFⅡ134E|个|200|1|2022/07/02|苏州硕普科林电子科技有限公司");
        binding.etCode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    String code = binding.etCode.getText().toString();
                    if (TextUtils.isEmpty(code)) {
                        showSoft();
                        return true;
                    }
                    binding.etCode.setText("");
                    addOrScan(code);
                }
                return true;
            }
        });
        showSoft();
    }

    private void addOrScan(String res) {
        hideSoft();
        if (!TextUtils.isEmpty(res)) {
            String[] all = res.replaceAll("\n", "").split("丨");
            if (all.length != 8) {
                all = res.replaceAll("\n", "").split("\\|");
            }
            if (all.length == 8) {
                all = res.replaceAll("\n", "").split("\\|");
            } else {
                showCDialog("扫码格式错误, 只能包含8个字端：" + all.length, null);
                return;
            }
            try {
                for (int i = 0; i < all.length; i++) {
                    if(TextUtils.isEmpty(all[i])){
                        showCDialog("扫码格式错误：[" + array[i] + "] 不能为空 :" + res, null);
                        return;
                    }
                    if (all[i].contains(" ")) {
                        showCDialog("扫码格式错误：[" + array[i] + "] 包含空格:" + res, null);
                        return;
                    }
                    if (i == 4 && !isNumeric(all[i])) {
                        showCDialog("扫码格式错误, 数量只能展示数字:" + res, null);
                        return;
                    }
                }
                // 存货编码|存货名称|规格型号|计量单位|数量|供应商批次号|生产日期|供应商名称
                initView(all);
                Toast.makeText(MainActivity.this, "二维码格式正确!!", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                showCDialog("二维码扫描解析异常，请联系管理员 e : " + e.getMessage(), null);
            }
        } else {
            showCDialog("扫描数据为空", null);
        }
    }

    private boolean isNumeric(String str){
        if(TextUtils.isEmpty(str)){
            return false;
        }
        for (char c : str.toCharArray()) {
            if(!Character.isDigit(c) && c != '.'){
                return false;
            }
        }
        return true;
    }

    private ItemInputLayout getItemInputLayout(int index, String name, String value,
                                               ItemInputLayout.ItemLayoutListener listener, int mode, boolean isNumber) {
        ItemInputLayout inputLayout = new ItemInputLayout(this);
        inputLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        inputLayout.getBinding().tvName.setText(name);
        inputLayout.getBinding().evValue.setEnabled(false);
        inputLayout.getBinding().evValue.setText(TextUtils.isEmpty(value) ? "" : value);
        if (isNumber) {
            inputLayout.getBinding().evValue.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
        }
        inputLayout.setItemMode(listener, mode);
        inputLayout.setIndex(index);
        return inputLayout;
    }

    private void showCDialog(String msg, CommonCallback<Object> commonCallback) {
        DialogUtils.showInfoDialog(this, msg, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                DialogUtils.closeInfoDialog();
                if (commonCallback != null) {
                    commonCallback.onResult(new Object());
                } else {
                    initView(null);
                }
            }
        });
    }

    private void showSoft() {
        binding.etCode.requestFocus();
        binding.etCode.setFocusable(true);
        binding.etCode.setFocusableInTouchMode(true);
        InputMethodManager imm = (InputMethodManager) binding.etCode.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(binding.etCode, 0);
    }

    private void hideSoft() {
        binding.etCode.requestFocus();
        InputMethodManager imm = (InputMethodManager) binding.etCode.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(binding.etCode.getWindowToken(), 0);
    }
}